package master

import (
	"crontab/common"
	"fmt"
	"github.com/samuel/go-zookeeper/zk"
	"time"
)

type WorkerMgr struct {
	client *zk.Conn
}

//全局单例
var (
	G_WorkerMgr *WorkerMgr
)

func InitWorkerMgr() (err error) {

	con, connChan, err := zk.Connect(G_Config.ZKEndPoint, time.Duration(G_Config.ZKConnectTimeout)*time.Millisecond)
	if err != nil {

		return err
	}

	for {
		isConnect := false
		select {
		case connEvent := <-connChan:
			if connEvent.State == zk.StateConnected {
				isConnect = true
				fmt.Println("connect to zookeeper server success")
				break
			}
		case _ = <-time.After(time.Duration(G_Config.ZKConnectTimeout) * time.Millisecond):
			goto ERR

		}
		if isConnect {

			break
		}
	}
	G_WorkerMgr = &WorkerMgr{
		client: con,
	}

	return

ERR:
	G_WorkerMgr.client.Close()
	return err
}

func (register *WorkerMgr) CreatePath(path string, data []byte, flag int32) (str string, err error) {

	var (
		exists bool
	)
	exists, _, err = register.client.Exists(path)
	if err != nil {
		return "", err
	}
	if !exists {
		str, err = register.client.Create(path, data, flag, zk.WorldACL(zk.PermAll))
		if err != nil && err != zk.ErrNodeExists {
			return "", err
		}

	}
	return path, err
}

func (register *WorkerMgr) SetData(path string, data []byte, flag int32) (err error) {
	if _, err = register.CreatePath(path, data, flag); err == zk.ErrNodeExists || err == nil {

		register.client.Set(path, data, -1)
		return nil
	}

	return err
}
func (workMgr *WorkerMgr) ListWorkers() (workers []string, err error) {
	workers = make([]string, 0)
	if workers, _, err = workMgr.client.Children(common.JOB_WORKS_PATH); err != nil {

		return
	}

	return
}
